﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

using ALE_Server.EC;

namespace ALE_Server.Plugin.Notifiers
{
    public class HTTPNotifier : Notifier
    {       
        private string m_Var;
        private string m_Host;
        private int m_Port;
        private string m_Path;
        private string m_PostVar = null;

        public HTTPNotifier(string uri)
            : base(uri)
        {
        }

        public override void Init(string uri)
        {
            if (uri.IndexOf("?") >= 0)
            {
                if (uri.IndexOf("&", uri.IndexOf("?")) >= 0)
                {
                    m_Var = uri.Substring(uri.IndexOf("?") + 1, uri.IndexOf("&", uri.IndexOf("?")));
                }
                else
                {
                    m_Var = uri.Substring(uri.IndexOf("?") + 1);
                }

                uri = uri.Substring(0, uri.IndexOf("?"));
            }

            m_Uri = new Uri(uri);

            m_Host = m_Uri.Host;
            m_Port = m_Uri.Port;
            m_Path = m_Uri.AbsolutePath;

            m_PostVar = m_Uri.Query;
        }

        public override void NotifySubscriber(ECReports reports)
        {           
            WebRequest Request = HttpWebRequest.Create(m_Uri);

            Stream RequestStream = Request.GetRequestStream();
            WriteToOutputStream(reports, RequestStream);
            RequestStream.Close();

            HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
         }

        public override string GetURIFromFields()
        {
            StringBuilder Result = new StringBuilder();
            Result.Append("http://");
            Result.Append(m_Host);
            Result.Append(":");
            Result.Append(m_Port);
            Result.Append("/");
            Result.Append(m_Path);
            if ((m_PostVar != null) && (m_PostVar.Length >0))
            {
                Result.Append("?");
                Result.Append(m_PostVar);
            }

            return Result.ToString();
        }
    }
}
